import React from 'react';
import { useEffect, useState } from 'react';

const App = () => {
  const [msg, setMsg] = useState('');

  useEffect(() => {
    // 执行副作用操作
    console.log('Component mounted');

    const socket = new WebSocket('ws://localhost:8201/api/pushMessage');

    socket.onopen = () => {
      console.log('WebSocket connection opened');
      // 在连接建立后，可以发送消息给服务器

      socket.send('Hello server!');
    };

    socket.onmessage = (event) => {
      console.log('Received message from server:', event.data);
      setMsg(event.data)
      // 处理从服务器接收到的消息
    };

    socket.onclose = () => {
      console.log('WebSocket connection closed');
      // 处理连接关闭事件
    };


    // 清理副作用操作
    return () => {
      console.log('Component unmounted');
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);



  return (
    <>
      <span>{msg}</span>
    </>
  )
};
export default App;
